# coding=utf-8
import json
import boto3
import datetime
from boto3 import Session

from core.m_logging import logger

aws_key = "AKIAIOFGB7H4GDSE5NJQ"
aws_secret = "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"
session = Session(aws_access_key_id=aws_key, aws_secret_access_key=aws_secret)
s3 = session.resource('s3')
bucket = s3.Bucket("core-products")
json.load_s3 = lambda f: json.load(bucket.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: bucket.Object(key=f).put(Body=json.dumps(obj))
# data = {"test":0}
# json.dump_s3(data, "key.json")  # saves json to s3://bucket/key
# data = json.load_s3("key.json")  # read json from s3://bucket/key


class S3Output(object):
    def __init__(self, s3_key_prefix):
        self.s3_key_prefix = s3_key_prefix

    def output(self, content):
        if content["success"]:
            batch_no = content["batch_no"]
            task_no = content["task_no"]
            today = datetime.datetime.now().strftime('%Y%m%d')
            current_node_path = "%s/%s/%s" % (self.s3_key_prefix, batch_no, task_no)
            file_name = "amazon_ansi_%s_%s_%s.json" % (content["node_no"], content["page_no"], today)
            output_path = "%s/%s" % (current_node_path, file_name)
            logger.info('output file to amazon s3 %s...' % output_path)
            json.dump_s3(content, output_path)
